<template>
	<view class="">
		<!-- 搜索框 -->
		<view class="padding">
			<custom-input v-model="keyword" holder='开始最求梦寐以求的公司...'></custom-input>
		</view>
		<view class="padding-left padding-right flex justify-between">
			热门岗位
			<text class="text-orange text-sm">查看更多</text>
		</view>
		<scroll-view scroll-x>
			<view class="padding flex hot-job">
				<company-job small v-for="item in hotjob" :key="item.objectId" :data="item"/>
			</view>
		</scroll-view>
		
		<view class="padding-left padding-right flex justify-between">
			最新岗位
			<text class="text-orange text-sm">查看更多</text>
		</view>
		<view class="padding">
			<company-job v-for="item in list" :key="item.objectId"
			 :data="item"
			 @click="handelDetail(item.objectId)"
			/>
			<custom-empty></custom-empty>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { http } from '../../utils/http'
import type { CompanyType } from '../../model/company'
import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';

// 横向列表渲染
const hotjob = ref<Array<CompanyType>>([])
let skip = Math.floor(Math.random() * 15 + 5)
http.get('classes/Company', {
	params: {
		limit: 6,
		skip
	}
}).then((res) => {
	hotjob.value = res.data.results
})

// 长列表渲染
const list = ref<Array<CompanyType>>([])
const page = ref(1)
const keyword = ref<string>('')

// 封装获取数据方法
const fetchData = async (resetPage: boolean = false) => {
	if (resetPage) {
		page.value = 1
	}

	const params: Record<string, any> = { limit: 10, skip: (page.value - 1) * 10 }

	if (keyword.value) {
		params.where = {
			$or: [
				{ companyName: { $regex: keyword.value, $options: "i" } },
				{ position: { $regex: keyword.value, $options: "i" } }
			]
		}
	}

	try {
		const res = await http.get('/classes/Company', { params })
		if (resetPage) {
			list.value = res.data.results
		} else {
			list.value = [...list.value, ...res.data.results]
		}
		if (res.data.results.length > 0) {
			page.value++
		}
	} catch (error) {
		console.error('获取数据失败:', error)
	}
}

// 初始化数据
fetchData(true)

// 搜索功能
watch(keyword, () => {
	fetchData(true)
})

// 下拉刷新
onPullDownRefresh(async () => {
	console.log('下拉刷新')
	await fetchData(true)
	uni.stopPullDownRefresh() // 主动关闭刷新动画
})

// 触底更新
onReachBottom(async () => {
	console.log('到底了')
	await fetchData(false)
})

const handelDetail = (id: string) => {
	uni.navigateTo({
		url: `/pages/company/detail?id=${id}`
	})
}
</script>

<style lang="scss">
page {
	background-color: #fff;
}
</style>